package com.hst.capacity.infra.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.hst.capacity.domain.common.constants.Constants;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Pattern;

//import org.apache.commons.lang3.StringEscapeUtils;

public class StringUtil {

    public static final String SEPARATOR=",";

    public static final String lineae_transversae = "-";
    //public static final Logger log=Logger.getLogger(StringUtil.class);

    /**
     * 判断指定object是否为null，如果为null，则返回空
     * @param obj
     * @return
     */
    public static String empty2Null(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj.toString().trim() == "") {
            return null;
        }
        return obj.toString().trim();
    }

    /**
     * 返回UTF8字符串
     * @param str
     * @return
     */
    public static String getStringUTF8(String str){
        try {
            return new String(str.getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 判断指定object是否为null，如果为null，则返回空
     * @param obj
     * @return
     */
    public static String convertNull(Object obj){
        return obj==null?"":obj.toString().trim();
    }

    /**
     * 判断指定字符串是否为非空
     * @param str
     * @return
     */
    public static boolean isNotBlank(String str){
        return str!=null&&!"".equals(str.trim())&&!"null".equalsIgnoreCase(str.trim())&&!"(null)".equalsIgnoreCase(str.trim());
    }

    /**
     * 判断指定字符串是否为空
     * @param str
     * @return
     */
    public static boolean isBlank(String str){
        return !isNotBlank(str);
    }

    // 随机密码
    public static String getRndPassword(int longNum) {
        String randPw = new String();
        randPw = convertNull((int) ((Math.random() * 9 + 1) * (Math.pow(10,longNum-1))));
        return randPw;
    }

    /**
     * 给图片名前加上前缀
     * @param imgPath
     * @param pre
     * @return
     */
    public static String prefix(String imgPath,String pre){
        if(StringUtil.isNotBlank(imgPath)&&imgPath.lastIndexOf("/")>-1){
            int index=imgPath.lastIndexOf("/");
            return imgPath.substring(0,index+1)+pre+imgPath.substring(index+1);
        }
        return imgPath;
    }

    /**
     * 过滤数组中重复的字符串
     * @param arrInput
     * @return
     */
    public static String[] removeDuplicate(String[] arrInput) {
        ArrayList<String> nStr = new ArrayList<String>();
        for (int i = 0; i < arrInput.length; i++) {
            if (!nStr.contains(arrInput[i].trim())) {
                nStr.add(arrInput[i].trim());
            }
        }
        return (String[]) nStr.toArray(new String[nStr.size()]);
    }

    /**
     * 将字符串分割成功整数数组
     * @param str
     * @return
     */
    public static Long [] splitToLongArray(String str){
        if(isBlank(str)){
            return null;
        }
        String [] arr=str.split(SEPARATOR);
        Long [] longArr=new Long[arr.length];
        try {
            for(int i=0;i<arr.length;i++){
                longArr[i]=Long.valueOf(arr[i]);
            }
        } catch (NumberFormatException e) {
            //log.error("Stringutil ", e);
            return null;
        }
        return longArr;
    }

    /**
     * 将数组转成字符串（逗号分割）
     * @param array
     * @return
     */
    public static String ArrayToString(String[] array) {

        String ret = null;
        if (array == null || array.length == 0) {
            return ret;
        }

        for (int i = 0; i < array.length; i++) {

            if (ret == null) {
                ret = array[i];
            } else {
                ret = ret + SEPARATOR + array[i];
            }
        }

        return ret;
    }

    /**
     * 将字符串转成数组（逗号分割）
     * @param str
     * @return
     */
    public static String[] StringToArray(String str) {

        if(isBlank(str)){
            return null;
        }

        String[] array = str.split(SEPARATOR);


        return array;
    }

    /**
     * 将字符串转成数组（逗号分割）
     * @param str
     * @return
     */
    public static List<String> StringToList(String str) {

        if(isBlank(str)){
            return null;
        }

        String[] array = str.split(SEPARATOR);
        List<String> list = Arrays.asList(array);

        return list;
    }

    public static String escapeHtml(String str){
        if(StringUtil.isBlank(str)) return str;

        str=str.replaceAll("<", "&lt;");
        str=str.replace(">", "&gt;");
        return str;
    }

//    public static String escapeJavaScript(String str){
//        return StringEscapeUtils.escapeEcmaScript(str);
//    }
//
//    public static String escapeXml(String str){
//        return StringEscapeUtils.escapeXml(str);
//    }
//
//    public static String escapeCsv(String str){
//        return StringEscapeUtils.escapeCsv(str);
//    }

    //判断字符串里面是否有数字（有一个也算有）
    public static boolean containsNumber(String str)
    {
        int isLD = 0;
        for(int i=0;i<str.length();i++)
        {
            char ch = str.charAt(i);
            if(Character.isDigit(ch))
            {
                return true;
            }

            else
                isLD++;
            {
            }
        }
        return false;
    }

    public static boolean isStrInString(String bigStr, String smallStr) {
        if (bigStr.toUpperCase().indexOf(smallStr.toUpperCase()) > -1)
            return true;
        return false;
    }


    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("-?[0-9]*.?[0-9]*");
        //Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    public static boolean isNotNumeric(String str){
        return !isNumeric(str);
    }

    public static boolean isAmount(String str){
        boolean ret = false;
        if(StringUtil.isNotBlank(str)&&StringUtil.isNumeric(str)&&((new BigDecimal(str)).compareTo(new BigDecimal(0))>0)){
            ret = true;
        }
        return ret;
    }

    public static boolean isNotAmount(String str){
        return !isAmount(str);
    }

    public static String formatEnName(String name){
        return name.trim().replaceAll("\\s{1,}", " ");
    }

    public static String removeSpace(String str){
        if(str!=null){
            return str.trim().replaceAll(" ", "");
        }
        else{
            return str;
        }
    }

    public static String encode(String str){
        String ret = "";
        try {
            ret = URLEncoder.encode(StringUtil.convertNull(str), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }

    public static String decode(String str){
        String ret = "";
        try {
            ret = URLDecoder.decode(StringUtil.convertNull(str),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ret;
    }

    public static String getFileExtName(String contentType){
        if(StringUtil.isBlank(contentType)){
            return "";
        }
        String fileExtName = "";
        if("image/jpeg".equalsIgnoreCase(contentType)||"image/pjpeg".equalsIgnoreCase(contentType)){
            fileExtName = "jpg";
        }
        else if("image/png".equalsIgnoreCase(contentType)||"image/x-png".equalsIgnoreCase(contentType)){
            fileExtName = "png";
        }
        else if("image/gif".equalsIgnoreCase(contentType)){
            fileExtName = "gif";
        }
        else if("application/pdf".equalsIgnoreCase(contentType)){
            fileExtName = "pdf";
        }
        else if("application/msword".equalsIgnoreCase(contentType)){
            fileExtName = "doc";
        }
        else if("application/vnd.openxmlformats-officedocument.wordprocessingml.document".equalsIgnoreCase(contentType)){
            fileExtName = "docx";
        }
        return fileExtName;
    }

    public static String convertAdParam(String param){
        String ret = convertNull(param);
        if(ret.indexOf(",")>0){
            ret = ret.substring(0, ret.indexOf(","));
        }
        return ret;
    }

    public static String formatPassword(String pass,int start,int end){
        if(pass.length()<end){
            return pass;
        }
        String stars="";
        for(int i=start;i<end;i++){
            stars =stars+"*";
        }
        return pass.substring(0,start)+stars+pass.substring(end, pass.length());

    }

    public static String removeSubStr(String str, String subStr){
        return str.replaceAll(subStr, "");
    }

    //string数组转int数组
    public static int[] stringArrayToIntArray(String[] numbers){
        int[] ia=new int[numbers.length];
        for(int i=0;i<numbers.length;i++){
            try{
                ia[i]=Integer.parseInt(numbers[i]);
            }catch (NumberFormatException e0){
                ia[i]=0;
                // System.out.println(e0);
            }
        }
        return ia;
    }

    //string数组转integer数组
    public static Integer[] stringArrayToIntegerArray(String[] numbers){
        Integer[] ia=new Integer[numbers.length];
        for(int i=0;i<numbers.length;i++){
            try{
                ia[i]=Integer.valueOf(numbers[i]);
            }catch (NumberFormatException e0){
                ia[i]=0;
                // System.out.println(e0);
            }
        }
        return ia;
    }

    //类似“70823,800032,”这样的数据去掉最后1个逗号
    public static String removeLastComma(String str){
        String finalResultStr = "";
        if(StringUtil.isNotBlank(str) && str.contains(",")){
            finalResultStr = str.toString().substring(0, str.toString().lastIndexOf(","));
        }
        return finalResultStr;
    }
    // 安定长，左补零
    public static String leftJoin(int value,int longNum) {
        return String.format("%0"+longNum+"d", value);
    }
    //订单号处理**+后五位
    public static String  orderIdFormat(String orderID) {
        if (orderID==null) {
            return "";
        }
        String orderId=orderID.substring(orderID.length()-5,orderID.length());
        orderId="**"+orderId;
        return orderId;
    }
    //得到短信条数、如果70字符就是1条，大于就+1
    public static int getCountSms(String content) {
        float b=content.length()/70f;
        String str=b+"";
        String size=str.substring(0, str.indexOf("."));
        String size1=str.substring(str.indexOf("."),str.length());
        int strSize = 0;
        if (Float.parseFloat(0+size1)>0) {
            strSize=Integer.parseInt(size)+1;

        }
        if (content.length()%70==0) {
            strSize=Integer.parseInt(size);
        }
        return strSize;

    }


    public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z" };


    public static String generateShortUuid() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();
    }

    public static String generateUuid() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        return uuid;
    }

    public static String createOrderID(int orderType) {
        return createOrderID(orderType,9);
    }

    public static String createOrderID(int orderType, int serviceType) {
        StringBuffer orderID = new StringBuffer();
        //专车
        if (orderType == 0) {
            orderID.append("ZC");
            //城际
        } else if (orderType == 1) {
            orderID.append("CJ");
            //快车
        } else if (orderType == 9) {
            if (serviceType == Constants.ServiceType.EXPRESS) {
                orderID.append("SN");
            } else if (serviceType == Constants.ServiceType.COUNTRYSIDE) {
                orderID.append("CX");
            }
        }
        Date date = DateUtil.date();
        String t = DateUtil.format(date, DatePattern.PURE_DATETIME_MS_PATTERN).substring(2);
        orderID.append(t).append(generateUuid().substring(0,8).toUpperCase());
        return orderID.toString();
    }

    public static int orderType(String idOrder) {
        String orderType = idOrder.substring(0,2);
        if (orderType.equals("ZC")) {
            return Constants.OrderModuleType.SPECIAL;
        } else if (orderType.equals("CJ")) {
            return Constants.OrderModuleType.INTERCITY;
        } else if (orderType.equals("SN") || orderType.equals("CX")) {
            return Constants.OrderModuleType.EXPRESS;
        }
        return -1;
    }

    /**
     * 临时使用，防止非运营城市调用地图计算
     * @return
     */
    public static List<String> openCityArr() {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("321,383");
        arrayList.add("383,321");

        arrayList.add("383,383");
        arrayList.add("321,321");

        arrayList.add("199,199");
        arrayList.add("199,209");
        arrayList.add("209,199");

        //石家庄
        arrayList.add("146,146");
        //石家庄-保定
        arrayList.add("139,146");
        arrayList.add("146,139");
        //石家庄-衡水
        arrayList.add("146,143");
        arrayList.add("143,146");
        //石家庄-北京
        arrayList.add("53,146");
        arrayList.add("146,53");
        //石家庄-天津
        arrayList.add("343,146");
        arrayList.add("146,343");
        //衡水
        arrayList.add("143,143");
        //衡水-天津
        arrayList.add("343,143");
        arrayList.add("143,343");
        //廊坊-石家庄
        arrayList.add("144,146");
        arrayList.add("146,144");
        //廊坊-天津
        arrayList.add("144,343");
        arrayList.add("343,144");
        //廊坊-北京
        arrayList.add("144,53");
        arrayList.add("53,144");
        //天津-北京
        arrayList.add("343,53");
        arrayList.add("53,343");
        //天津-唐山
        arrayList.add("343,147");
        arrayList.add("147,343");

        //南宁
        arrayList.add("108,108");
        //河池
        arrayList.add("104,104");
        //南宁-河池
        arrayList.add("104,108");
        arrayList.add("108,104");
        //柳州-河池
        arrayList.add("104,107");
        arrayList.add("107,104");

        //东莞
        arrayList.add("78,78");

        //广州，深圳，东莞
        //arrayList.add("80,80");
        arrayList.add("80,91");
        arrayList.add("91,80");
        //arrayList.add("91,91");
        arrayList.add("91,78");
        arrayList.add("78,91");
        arrayList.add("80,78");
        arrayList.add("78,80");
        arrayList.add("82,80");
        arrayList.add("80,82");
        arrayList.add("97,80");
        arrayList.add("80,97");
        //广州-佛山
        arrayList.add("79,80");
        arrayList.add("80,79");

        //汕尾
        arrayList.add("89,89");
        //汕尾-深圳
        arrayList.add("91,89");
        arrayList.add("89,91");
        //汕尾-惠州
        arrayList.add("82,89");
        arrayList.add("89,82");

        //南京
        arrayList.add("224,224");
        arrayList.add("224,226");
        arrayList.add("226,224");
        arrayList.add("224,229");
        arrayList.add("229,224");
        arrayList.add("226,229");
        arrayList.add("229,226");

        //温州
        arrayList.add("391,391");

        return arrayList;
    }

    /**
     * 临时使用，防止非运营城市调用地图计算
     * @return
     */
    public static List<String> grabCityArr() {
        ArrayList<String> arrayList = new ArrayList<>();
        //南宁
        arrayList.add("108,108");
        //柳州
        arrayList.add("107,107");
        //河池
        arrayList.add("104,104");
        //南宁-河池
        arrayList.add("104,108");
        arrayList.add("108,104");
        //柳州-河池
        arrayList.add("104,107");
        arrayList.add("107,104");

        //东莞
        arrayList.add("78,78");

        //广州，深圳，东莞
        arrayList.add("80,80");
        arrayList.add("80,91");
        arrayList.add("91,80");
        //arrayList.add("91,91");
        arrayList.add("91,78");
        arrayList.add("78,91");
        arrayList.add("80,78");
        arrayList.add("78,80");
        arrayList.add("82,80");
        arrayList.add("80,82");
        arrayList.add("97,80");
        arrayList.add("80,97");
        //广州-佛山
        arrayList.add("79,80");
        arrayList.add("80,79");

        //汕尾
        arrayList.add("89,89");
        //汕尾-深圳
        arrayList.add("91,89");
        arrayList.add("89,91");

        //南京
        arrayList.add("224,224");
        arrayList.add("224,226");
        arrayList.add("226,224");
        arrayList.add("224,229");
        arrayList.add("229,224");
        arrayList.add("226,229");
        arrayList.add("229,226");

        //温州
        arrayList.add("391,391");

        return arrayList;
    }

    public static String UnicodeToChinese(String theString ) {

        // 转换
        char aChar;

        int len = theString.length();

        StringBuffer outBuffer = new StringBuffer(len);

        for (int x = 0; x < len;) {

            aChar = theString.charAt(x++);

            if (aChar == '\\') {

                aChar = theString.charAt(x++);

                if (aChar == 'u') {

                    // Read the xxxx

                    int value = 0;

                    for (int i = 0; i < 4; i++) {

                        aChar = theString.charAt(x++);

                        switch (aChar) {

                            case '0':

                            case '1':

                            case '2':

                            case '3':

                            case '4':

                            case '5':

                            case '6':

                            case '7':

                            case '8':

                            case '9':

                                value = (value << 4) + aChar - '0';

                                break;

                            case 'a':

                            case 'b':

                            case 'c':

                            case 'd':

                            case 'e':

                            case 'f':

                                value = (value << 4) + 10 + aChar - 'a';

                                break;

                            case 'A':

                            case 'B':

                            case 'C':

                            case 'D':

                            case 'E':

                            case 'F':

                                value = (value << 4) + 10 + aChar - 'A';

                                break;

                            default:

                                throw new IllegalArgumentException(

                                        "Malformed   \\uxxxx   encoding.");

                        }

                    }

                    outBuffer.append((char) value);

                } else {

                    if (aChar == 't')

                        aChar = '\t';

                    else if (aChar == 'r')

                        aChar = '\r';

                    else if (aChar == 'n')

                        aChar = '\n';

                    else if (aChar == 'f')

                        aChar = '\f';

                    outBuffer.append(aChar);

                }

            } else

                outBuffer.append(aChar);

        }

        return outBuffer.toString();

    }

}
